<?php

namespace Platform\Repository\Admin;

use Illuminate\Http\Request;
use Platform\Models\Admin\Department;
use Platform\Repository\Repository;

class DepartmentRepository extends Repository
{

    public function model()
    {
        return  Department::class;
    }

    public function getOneByName($name)
    {
        return $this->model
            ->where('name', '=', $name)
            ->first();
    }

    public function getOneByNameExpectThis($name,$id)
    {
        return $this->model
            ->where('name', '=', $name)
            ->where('id', '<>', $id)
            ->first();
    }

    /**
     * 清空角色默认字段
*/
    public function clearDefault()
    {
        $this->model->where('is_default',Department::DEFAULT_YES)->update(['is_default' => Department::DEFAULT_NO]);
    }

    /**
     * 获取默认角色
     */
    public function getDefault()
    {
        return $this->model
            ->where('is_default', Department::DEFAULT_YES)
            ->first();
    }


    /**
     * 通过关键词查询
     * @param Request $request
     * @return mixed
     */
    public function screen(Request $request){
        $builder = $this->model->newQuery();

        $name = $request->get('name',null);
        $describe = $request->get('describe',null);

        if ($name){
            $builder->where('name', 'like', '%'.$name.'%');
        }
        if ($describe){
            $builder->where('describe', 'like', '%'.$describe.'%');
        }
        $builder->orderByDesc('created_at');

        return $builder->get();
    }

}
